package com.skyeye;

import com.skyeye.entity.User;
import com.skyeye.mapper.UserMapper;
import com.skyeye.util.DatabaseUtil;
import com.skyeye.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.time.LocalDateTime;

import static org.junit.Assert.*;

/**
 * 简单的MyBatis测试类
 * 用于验证MyBatis基本功能
 */
public class SimpleMyBatisTest {
    
    private SqlSession sqlSession;
    private UserMapper userMapper;
    
    @Before
    public void setUp() {
        try {
            // 创建测试表
            DatabaseUtil.createTestTable();
            
            // 获取SqlSession和Mapper
            sqlSession = MyBatisUtil.getSqlSession();
            userMapper = sqlSession.getMapper(UserMapper.class);
            
            System.out.println("🚀 开始执行简单MyBatis测试...");
            
        } catch (Exception e) {
            fail("MyBatis初始化失败: " + e.getMessage());
        }
    }
    
    @After
    public void tearDown() {
        try {
            // 清空测试数据
            DatabaseUtil.truncateTestTable();
            
            // 关闭SqlSession
            if (sqlSession != null) {
                MyBatisUtil.closeSqlSession(sqlSession);
            }
            
            System.out.println("🧹 简单MyBatis测试完成，清理测试数据");
            
        } catch (Exception e) {
            System.err.println("清理测试数据时出错: " + e.getMessage());
        }
    }
    
    /**
     * 测试MyBatis基本功能
     */
    @Test
    public void testBasicMyBatisFunction() {
        try {
            // 准备测试数据
            User testUser = new User("测试用户", "test@example.com", 25, "13800138000");
            testUser.setCreateTime(LocalDateTime.now());
            testUser.setUpdateTime(LocalDateTime.now());
            
            // 执行插入
            int affectedRows = userMapper.insertUser(testUser);
            
            assertEquals("应该插入1条记录", 1, affectedRows);
            assertNotNull("用户ID应该被设置", testUser.getId());
            
            System.out.println("✅ MyBatis基本功能测试成功！");
            System.out.println("插入的用户ID: " + testUser.getId());
            
        } catch (Exception e) {
            fail("MyBatis基本功能测试失败: " + e.getMessage());
        }
    }
}
